package com.mywork.mvpkodeinxml.net.service

import com.mywork.mvpkodeinxml.net.api.UploadApi
import com.mywork.mvpkodeinxml.model.response.BaseEntity
import com.mywork.mvpkodeinxml.net.RetrofitFactory
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File


class UploadService {

    fun upload(
        userCode: String,
        userPassword: String,
        formtype: String,
        taskid: String,
        file: File
    ): Observable<BaseEntity> {
        val fileBody = file.asRequestBody("image/*".toMediaTypeOrNull())
        return RetrofitFactory.create(UploadApi::class.java)
            .upload("120041", "", "99", "7ee8a8472b734f268bb473256fb1a6d3", file.name, fileBody)

    }

    //服务器不支持Multipart方式上传
    fun uploadMultipart(
        userCode: String,
        userPassword: String,
        formtype: String,
        taskid: String,
        file: File
    ): Observable<BaseEntity> {
        val fileBody = file.asRequestBody("image/*".toMediaTypeOrNull())
        val paramMap = mutableMapOf<String,RequestBody>(Pair("file\"; filename=\""+file.name+"\"",fileBody))
        //addMultiPart(paramMap, "file", file);
        Logger.d(file.name)
        return RetrofitFactory.create(UploadApi::class.java)
            .uploadMultipart("120041", "", "99", "7ee8a8472b734f268bb473256fb1a6d3", file.name, paramMap)

    }

    private fun addMultiPart(paramMap: MutableMap<String, RequestBody>, key: String, obj: Any) {
        if (obj is String) {
            val body = obj.toRequestBody("text/plain;charset=UTF-8".toMediaTypeOrNull())
            paramMap[key] = body
        } else if (obj is File) {
            val body = obj.asRequestBody("multipart/form-data;charset=UTF-8".toMediaTypeOrNull())
            paramMap[key + "\"; filename=\"" + obj.name + ""] = body
        }
    }

}